package com.wzdigit.wms.basic.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;

public class NetUtils {

	//获取用户实际ip
	public static String getIpAddr(HttpServletRequest request) {
		try {
			String ipAddress = request.getHeader("x-forwarded-for");
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress))
				ipAddress = request.getHeader("Proxy-Client-IP");
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress))
				ipAddress = request.getHeader("WL-Proxy-Client-IP");
			if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
				ipAddress = request.getRemoteAddr();
				if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
					// 根据网卡取本机配置的IP
					InetAddress	inet = InetAddress.getLocalHost();
					ipAddress = inet.getHostAddress();
				}
			}
			// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
			if (ipAddress != null && ipAddress.length() > 15) {
				if (ipAddress.indexOf(",") > 0)
					ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
			return ipAddress;
		} catch (Exception e) {}
		return null;
	}
	
	public static String getResponseStr(HttpServletRequest request) throws IOException {
		StringBuffer sb = new StringBuffer();
		InputStream inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null)
			sb.append(s);
		in.close();
		inputStream.close();
		return sb.toString();
	}
}
